rednet.open("back")
os.loadAPI("button")
local m = term
local menuType = "mainMenu" 

local mainCompID = 0
local frameCompID = 6



local frameCoords = {}
frameCoords["x"] = 0
frameCoords["y"] = 0
frameCoords["z"] = 0

function sendMessage(message)
    rednet.send(mainCompID, message)
end

function mainMenu()
	m.clear()
	button.clearTable()
	button.setTable("Up", frameMove, "Up", 3, 13, 1, 1)
	button.setTable("Down", frameMove, "Down", 15, 25, 1, 1)
	button.setTable("Forward", frameMove, "Forward", 3, 13, 3, 3)
	button.setTable("Backward", frameMove, "Backward", 15, 25, 3, 3)
	button.setTable("Bedrock", textMessage, "Bedrock", 3, 13, 5, 5)
	button.setTable("SeaLevel", textMessage, "SeaLevel", 15, 25, 5, 5)
	button.setTable("SendItems", textMessage, "SendItems", 3, 13, 7, 7)
--	button.setTable("Dome", textMessage, "Dome", 15, 25, 7, 7)
	button.setTable("Cycle", textMessage, "Cycle", 15, 25, 7, 7)
	button.setTable("NextCycle", textMessage, "NextCycle", 15, 25, 9, 9)
	button.setTable("AutoMode", textMessage, "AutoMode", 3, 13, 13, 13)
	button.setTable("STOP", textMessage, "STOP", 15, 25, 13, 13)
	button.setTable("Refresh Coords", setFrameCoords, "", 3, 25, 17, 17)
	button.label(1,20,"Frame Coords: "..frameCoords["x"]..","..frameCoords["y"]..","..frameCoords["z"])
	checkCurrentFunction()
	button.screen()
end

function getFrameLoc()
	local data = {}
	local id,msg,proto
	repeat
		rednet.send(frameCompID, "GPS")
		id,msg,proto = rednet.receive(0.1)
	until id == frameCompID
	data = textutils.unserialize(msg)
	return data["x"], data["y"], data["z"]
end

function setFrameCoords()
	button.toggleButton("Refresh Coords")
	frameCoords["x"], frameCoords["y"], frameCoords["z"] = getFrameLoc()
	button.toggleButton("Refresh Coords")
end

function frameMove(message)
	--button.toggleButton(message)
	local data = {}
	data[0] = "moveFrame"
	data[1] = message
	sendMessage(textutils.serialize(data))
	--waitComplete()
	--button.toggleButton(message)
end

function textMessage(message)
	local data = {}
	data[0] = message
	sendMessage(textutils.serialize(data))
end

function checkCurrentFunction()
	local id,msg,proto
	repeat
		textMessage("CurrentFunction")
		id,msg,proto = rednet.receive(0.1)
	until msg
	data = textutils.unserialize(msg)
	if data[0] ~= "" then
		button.setButton(data[0], true)
	end
	button.setButton("AutoMode", data[1])
	button.setButton("Cycle", data[2])
end

function displayScreen()
--	setFrameCoords()
	mainMenu()
	local timerCode = 0
	timerCode = os.startTimer(1)
	local event,side, x, y
	repeat
	--	event, side, x, y = os.pullEvent("mouse_click")
	event, side, x, y = os.pullEvent()
	--	print(event)
	--	sleep(0.2)
	--	print(event..":"..side)
		
	until side == timerCode or event=="mouse_click" or event == "mouse_drag"
	if event == "mouse_click" or event == "mouse_drag" then
		os.cancelTimer(timerCode)
		button.checkxy(x,y)	
	end
end

while true do
	displayScreen()
end
